use std::sync::Arc;
use crate::middlewares::redis_client;
use crate::services::user_service::UserService;
use actix_web::{web, HttpResponse};
use log::{error, info};
use nonce::Nonce;
use sea_orm::DatabaseConnection;

// User Controller Layer
// Get all users
pub async fn get_all_users(db: web::Data<Arc<DatabaseConnection>>) -> HttpResponse {
    // test redis
    {
        error!("test redis begin=======");
        let redis = redis_client::get_redis_client().await;
        let value = redis.get("name").unwrap();
        info!("Got value from Redis asynchronously: {}", value);
        error!("test redis end=======");
    }

    UserService::get_all_users(db).await.unwrap_or_else(|e| {
        error!("Failed to fetch users: {:?}", e);
        HttpResponse::InternalServerError().body("Failed to fetch users")
    })
}

// delete user by id
pub async fn delete_user_by_id(
    db: web::Data<Arc<DatabaseConnection>>,
    path: web::Path<i64>,
) -> HttpResponse {
    let user_id = path.into_inner();
    log::warn!("will del user id is [{}]", user_id);
    UserService::delete_user_by_id(db, user_id)
        .await
        .unwrap_or_else(|e| {
            error!("Failed to delete user: {:?}", e);
            HttpResponse::InternalServerError().body("Failed to delete user")
        })
}

pub async fn get_nonce() -> HttpResponse {
    log::error!("test get_nonce.");
    let nonce = Nonce::generate().await;
    let mut iat1 = nonce::get_system_time();
    error!(
        "test redis begin=======iat ={}--value = {},---signature=",
        nonce.iat, nonce.value
    );

    let mut input = nonce::ValidateNonceParams {
        valid_period: iat1,
        nonce: nonce,
    };
    error!("input is {:?}", input);
    let res = nonce::validate_nonce(input).await;
    error!("res is  {},---{}", res.is_valid, res.message);
    HttpResponse::Ok().body("get_nonce ok".to_string())
}
